package com.music.ui.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.download.DownloadInfo;
import com.lzy.okserver.download.DownloadManager;
import com.lzy.okserver.download.DownloadService;
import com.lzy.okserver.listener.DownloadListener;
import com.music.R;
import com.music.ui.activity.ArtistInfoActivity;
import com.music.application.Constants;
import com.music.entity.online.OnlineArtistInfo;
import com.music.entity.online.OnlineMusicInfo;
import com.music.entity.online.SongPlay;
import com.music.loader.Api;
import com.music.loader.DataRequest;
import com.music.utils.CacheUtil;
import com.music.utils.StringUtil;
import com.music.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/9/21.
 */
public class BoardMusicListAdapter extends BaseAdapter {

    private Context mContext;
    private List<OnlineMusicInfo> mList = new ArrayList<>();

    public BoardMusicListAdapter(Context context, List<OnlineMusicInfo> list) {
        mContext = context;
        mList = list;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final OnlineMusicInfo item = mList.get(position);
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_online_music, null);
            holder.iv_cover = (ImageView) convertView.findViewById(R.id.iv_cover);
            holder.tv_music_name = (TextView) convertView.findViewById(R.id.tv_music_name);
            holder.tv_artist_name = (TextView) convertView.findViewById(R.id.tv_artist_name);
            holder.rlMore = (RelativeLayout) convertView.findViewById(R.id.rlMore);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Glide.with(mContext)
                .load(item.getPicSmall())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(holder.iv_cover);
        holder.tv_music_name.setText(item.getArtistName());
        holder.tv_artist_name.setText(item.getTitle());
        holder.rlMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onMoreClick(position);
            }
        });

        return convertView;
    }

    class ViewHolder {
        ImageView iv_cover;
        TextView tv_music_name;
        TextView tv_artist_name;
        RelativeLayout rlMore;
    }

    private void onMoreClick(int position) {
        final OnlineMusicInfo onlineMusicInfo = mList.get(position);
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle(onlineMusicInfo.getTitle());
        dialog.setItems(R.array.online_music_dialog, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:// 分享
                        share(onlineMusicInfo);
                        break;
                    case 1:// 下载
                        download(onlineMusicInfo);
                        break;
                    case 2:// 查看歌手信息
                        getArtistInfo(onlineMusicInfo);
                        break;
                }
            }
        });
        dialog.show();
    }

    private void getArtistInfo(OnlineMusicInfo onlineMusicInfo) {
        DataRequest.getInstance().getArtistInfo(Api.METHOD_ARTIST_INFO, onlineMusicInfo.getTingUid(), new DataRequest.Callback<OnlineArtistInfo>() {
            @Override
            public void onSuccess(OnlineArtistInfo data) {
                Log.d("dingfeng", "intro:" + data.getIntro());
                Intent intent = new Intent();
                intent.setClass(mContext, ArtistInfoActivity.class);
                intent.putExtra("artistInfo", data);
                mContext.startActivity(intent);
            }

            @Override
            public void onError(String err) {

            }
        });
    }

    private void share(final OnlineMusicInfo onlineMusicInfo) {
        DataRequest.getInstance().getOnlineUri(Api.METHOD_DOWNLOAD_MUSIC, onlineMusicInfo.getSongId(), new DataRequest.Callback<SongPlay>() {
            @Override
            public void onSuccess(SongPlay data) {
                String fileLink = "";
                if (data != null && data.getBitrate() != null) {
                    fileLink = data.getBitrate().getFilelink();
                }
                if (!StringUtil.isEmpty(fileLink)) {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_TEXT, data.getBitrate().getFilelink());
                    mContext.startActivity(Intent.createChooser(intent, mContext.getString(R.string.share)));
                } else {
                    Toast.makeText(mContext, R.string.file_link_error, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String err) {
                Toast.makeText(mContext, R.string.file_link_error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void download(final OnlineMusicInfo onlineMusicInfo) {
        DataRequest.getInstance().getOnlineUri(Api.METHOD_DOWNLOAD_MUSIC, onlineMusicInfo.getSongId(), new DataRequest.Callback<SongPlay>() {
            @Override
            public void onSuccess(SongPlay data) {
                String fileLink = "";
                if (data != null && data.getBitrate() != null) {
                    fileLink = data.getBitrate().getFilelink();
                }
                if (!StringUtil.isEmpty(fileLink)) {
                    download(onlineMusicInfo, fileLink);
                } else {
                    ToastUtil.showToast(R.string.download_link_error);
                }
            }

            @Override
            public void onError(String err) {
                Toast.makeText(mContext, err, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void download(final OnlineMusicInfo onlineMusicInfo, String url) {
        DownloadManager downloadManager = DownloadService.getDownloadManager();
        downloadManager.setTargetFolder(Constants.DOWNLOAD);
        if (downloadManager.getDownloadInfo(url) != null) {
            Toast.makeText(mContext, R.string.download_task_exist, Toast.LENGTH_SHORT).show();
        } else {
            GetRequest request = OkGo.get(url);
            CacheUtil.getInstance(mContext).put(url, onlineMusicInfo);
            downloadManager.addTask(onlineMusicInfo.getTitle() + ".mp3", url, request, new DownloadListener() {

                @Override
                public void onAdd(DownloadInfo downloadInfo) {
                    super.onAdd(downloadInfo);
                    ToastUtil.showToast(mContext.getString(R.string.add_download_task, onlineMusicInfo.getTitle()));
                }

                @Override
                public void onProgress(DownloadInfo downloadInfo) {
                }

                @Override
                public void onFinish(DownloadInfo downloadInfo) {
                }

                @Override
                public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
                    ToastUtil.showToast(R.string.download_error);
                }

            });
        }
    }

}
